/**
 * Project: complex.spring.advance
 * 
 * File Created at 2010-4-19
 * $Id$
 * 
 * Copyright 2008 Alibaba.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Alibaba Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Alibaba.com.
 */
package com.complex.spring.advance.service.impl;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;

import com.complex.spring.advance.service.ITestB;

/**
 * @description:演示bean手动注册过程
 * @author gaoliang
 * @date 2010-4-19
 * @version 1.0
 */
public class TestSpringIOC {
    public static void main(String[] args) {
    	//beanRegistry 它实现了BeanFactory,又实现BeanDefinitionRegistry
        DefaultListableBeanFactory beanRegistry = new DefaultListableBeanFactory();
        BeanFactory container = (BeanFactory)bindViaCode(beanRegistry);
        ITestB testB = (ITestB)container.getBean("testB");
        testB.print();
    }
    
    private static BeanFactory bindViaCode(BeanDefinitionRegistry beanRegistry){
        /**注册行为,是容器启动时需要做的事情 ApplicationContext默认启动时初始化BEAN*/
        //定义bean
        AbstractBeanDefinition testA = new RootBeanDefinition(TestAImpl.class);
        AbstractBeanDefinition testB = new RootBeanDefinition(TestBImpl.class);
        //将bean定义注册到容器中
        beanRegistry.registerBeanDefinition("testA", testA);
        beanRegistry.registerBeanDefinition("testB", testB);
        
        /**Bean实例化阶段 初始化各个bean*/
        //构造方法注入
        //ConstructorArgumentValues argValues = new ConstructorArgumentValues();
        //argValues.addIndexedArgumentValue(0, testA);
        //testB.setConstructorArgumentValues(argValues);
        
        //setter注入
        MutablePropertyValues propertyValues = new MutablePropertyValues();
        propertyValues.addPropertyValue("testA", testA);
        testB.setPropertyValues(propertyValues);
        
        //beanRegistry就是一个IoC容器
        return (BeanFactory)beanRegistry;
    }
}
